package com.starmark.auth.common.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.starmark.auth.common.dto.SecurityUser;
import com.starmark.auth.common.util.UserUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.lang.Nullable;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginHandlerInterceptor extends BaseInterceptor {

    private static final String X_CLIENT_TOKEN = "x-client-token";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        String gatewayUser = request.getHeader(X_CLIENT_TOKEN);
        if (StringUtils.isNotEmpty(gatewayUser)) {
            // 已经登陆放行请求
            SecurityUser sysUser = JSONObject.parseObject(this.getUsername(gatewayUser), SecurityUser.class);

            // 已登陆的用户加入线程当中
            UserUtil.add(sysUser);


        }
        return true;

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) {

        UserUtil.remove();

    }
    /**
     * 获得token中的信息无需secret解密也能获得
     *
     * @return token中包含的用户名
     */
    private  String getUsername(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("username").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

}
